import React, { useState, useEffect } from "react"
import styled from "styled-components"
import { useNavigate } from "react-router-dom"
import loader from "../assets/loader.gif"
import { ToastContainer, toast } from "react-toastify"
import "react-toastify/dist/ReactToastify.css"
import axios from "axios"
import { setAvatarRoute } from "../utils/APIRoutes"
import multiavatar from "@multiavatar/multiavatar/esm"
import { Buffer } from "buffer"
import { BiRefresh } from "react-icons/bi"

export default function SetAvatar() {
  const navigate = useNavigate()

  const [avatars, setAvatars] = useState([])
  const [isLoading, setIsLoading] = useState(true)
  const [selectedAvatar, setSelectedAvatar] = useState(undefined)

  const toastOptions = {
    position: "bottom-right",
    autoClose: 5000,
    pauseOnHover: true,
    draggable: true,
    hideProgressBar: true,
    theme: "dark",
  }

  useEffect(() => {
    if (!localStorage.getItem("snappy-user")) {
      navigate("/login")
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const setProfilePicture = async () => {
    if (selectedAvatar === undefined) {
      toast.error("Please select an avatar", toastOptions)
    } else {
      const user = await JSON.parse(localStorage.getItem("snappy-user"))
      await axios
        .post(`${setAvatarRoute}/${user._id}`, {
          image: avatars[selectedAvatar],
        })
        .then((res) => {
          if (res.data.status) {
            user.isAvatarImageSet = true
            user.avatarImage = res.data.image
            localStorage.setItem("snappy-user", JSON.stringify(user))
            navigate("/")
          } else {
            toast.error("Cannot find the user.", toastOptions)
          }
        })
        .catch(() => {
          toast.error("Unknown error.", toastOptions)
        })
    }
  }

  useEffect(() => {
    handleRefresh()
  }, [])

  const handleRefresh = () => {
    setIsLoading(true)
    const data = []
    for (let i = 0; i < 4; i++) {
      const image = multiavatar(Math.round(Math.random() * 10000))
      const buffer = new Buffer(image)
      data.push(buffer.toString("base64"))
    }
    setAvatars(data)
    setTimeout(() => {
      setIsLoading(false)
    }, 1500)
  }

  return (
    <>
      {isLoading ? (
        <Container>
          <img src={loader} alt="loader" className="loader" />
        </Container>
      ) : (
        <Container>
          <div className="title-container">
            <h1>Pick an avatar as your profile picture</h1>
            <Button onClick={() => handleRefresh()}>
              <BiRefresh />
            </Button>
          </div>
          <div className="avatars">
            {avatars.map((avatar, index) => {
              return (
                <div
                  key={index}
                  className={`avatar ${
                    selectedAvatar === index ? "selected" : ""
                  }`}
                >
                  <img
                    src={`data:image/svg+xml;base64,${avatar}`}
                    alt="avatar"
                    onClick={() => setSelectedAvatar(index)}
                  />
                </div>
              )
            })}
          </div>
          <button className="submit-btn" onClick={() => setProfilePicture()}>
            Set as profile picture
          </button>
        </Container>
      )}
      <ToastContainer />
    </>
  )
}

const Container = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 3rem;
  background-color: #131324;
  height: 100vh;
  weight: 100vw;

  .loader {
    max-inline-size: 100%;
  }

  .title-container {
    display: flex;
    gap: 1rem;
    h1 {
      color: white;
    }
  }

  .avatars {
    display: flex;
    gap: 2rem;
    .avatar {
      border: 0.4rem solid transparent;
      padding: 0.4rem;
      border-radius: 5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: 0.5s ease-in-out;

      img {
        height: 6rem;
      }
    }

    .selected {
      border: 0.4rem solid #4e0eff;
    }
  }

  .submit-btn {
    background-color: #997af0;
    color: white;
    padding: 1rem 2rem;
    border: none;
    font-weight: bold;
    cursor: pointer;
    border-radius: 0.4rem;
    text-transform: uppercase;
    font-size: 1rem;
    transition: 1s ease-in-out;
    &:hover {
      background-color: #4e0eff;
    }
  }
`

const Button = styled.button`
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.5rem;
  border-radius: 5rem;
  background-color: #997af0;
  border: none;
  cursor: pointer;
  transition: 1s ease-in-out;
  &:hover {
    background-color: #4e0eff;
  }
  svg {
    font-size: 1.3rem;
    color: #ebe7ff;
  }
`
